<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// | Date: 2019/03/15
// | Time:上午 10:26
// +----------------------------------------------------------------------
namespace plugins\wechat_login\controller;

use cmf\controller\PluginBaseController;
use plugins\wechat_login\lib\WechatOauth2;
//use think\Db;
use think\facade\Db;
use api\v1\service\UserPublicService;

class WechatController extends PluginBaseController
{
    /**
     * 微信登录链接
     * https://f.kjdll.cn:9999/plugin/wechat_login/wechat/login
     * @return \think\response\Redirect
     * @throws \Exception
     */
    public function login()
    {
        $wechatOauth2 = new WechatOauth2();
        $config       = $this->getPlugin()->getConfig();
        $wechatOauth2->setAppKey($config['app_id']);
        $wechatOauth2->setAppSecret($config['app_secret']);
        //$url = cmf_plugin_url('WechatLogin://wechat/callback', [], true);
        $url = "https://f.kjdll.cn:9999/plugin/wechat_login/wechat/callback";
        //$url = "https%3A%2F%2Ff.kjdll.cn%3A9999%2Fplugin%2Fwechat_login%2Fwechat%2Fcallback";
        $wechatOauth2->setCallback($url);

        return redirect($wechatOauth2->getRequestCodeURL());
    }

    /**
     * 第三方登录授权回调地址
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @throws \Exception
     */
    public function callback()
    {
        //var_dump($this->request->param());
        /**
         * { ["code"]=> string(32) "031ag00w3gJMv43klm1w3p9iGK0ag00K" 
         * ["state"]=> string(5) "STATE" 
         * ["_plugin"]=> string(12) "wechat_login" 
         * ["_controller"]=> string(6) "wechat" 
         * ["_action"]=> string(8) "callback" } 
         */

        $code = $this->request->param('code');
        if (empty($code)) {
            $this->error('参数不正确');
        }
        $wechatOauth2 = new WechatOauth2();
        $config       = $this->getPlugin()->getConfig();
        $wechatOauth2->setAppKey($config['app_id']);
        $wechatOauth2->setAppSecret($config['app_secret']);
        //var_dump("appid");
        //var_dump($config['app_id']);
        //var_dump("app_secret");
        //var_dump($config['app_secret']);
        $token = $wechatOauth2->getAccessToken($code);
        //var_dump($token);
        //获取当前登录用户信息
        if (is_array($token)) {

            $data = $wechatOauth2->call('sns/userinfo');

            //var_dump($data);
            /**
             * array(10) { 
             * ["openid"]=> string(28) "ocs7O67mv5obM2xjY0F3Xzv26XtA" 
             * ["nickname"]=> string(12) "夕阳余晖" 
             * ["sex"]=> int(0) ["language"]=> string(0) "" 
             * ["city"]=> string(0) "" 
             * ["province"]=> string(0) "" 
             * ["country"]=> string(0) "" 
             * ["headimgurl"]=> string(152) "https://thirdwx.qlogo.cn/mmopen/vi_32/D9hhtg7QVjfHAgRvdk59TfbscOXEVgkQu1v4reLZpE3JQEcq2DbPJqyiakjd8a7R4w2fShAFNBkDzL6qYMxWpF5L15Y4ia7MT5pDV1eEqeMiag/132" 
             * ["privilege"]=> array(0) { } 
             * ["unionid"]=> string(28) "opKXO61L5ZYgdvwEoOiw35bCIYCs" }    ////同一个开放平台添加的web页和小程序，获得的unionid是一样的
             */

            $userInfo = [
                'third_party' => 'wechat',
                'nickname'    => $data['nickname'],
                'avatar'      => $data['headimgurl'],
                'union_id'    => $data['unionid'],          //新增，用于微信WEB页登录 与 微信小程序登录 识别同一个用户
            ];

            $sessionOauthBang = session('oauth_bang');
            if (!empty($sessionOauthBang)) {
                //$this->_bang_handle($userInfo, 'wechat', $token);
                $this->loginHandle($userInfo, 'wechat', $token);
            } else {
                $this->loginHandle($userInfo, 'wechat', $token);
            }
        } else {
            $this->success('登录失败1！', $this->_getLoginRedirect());
        }
    }

    /**
     * 处理第三方登陆
     * @param        $userInfo
     * @param        $type
     * @param  array $token
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function loginHandle($userInfo, $type, $token)
    {
        //$findThirdPartyUser = Db::name('third_party_user')->where(["third_party" => $type, "openid" => $token['openid']])->find();
        //不使用openid，因为同一个开放平台要兼容微信web登录和小程序登录，使用unionid识别即可
        $findThirdPartyUser = Db::name('third_party_user')->where(["union_id" => $userInfo['union_id']])->find();

        $needRegister       = true;
        if ($findThirdPartyUser) {
            $findUser = Db::name('user')->where(["id" => $findThirdPartyUser['user_id']])->find();
            if ($findUser) {
                $needRegister = false;
                if ($findUser['user_status'] == '0') {
                    $this->error('您已经被列入黑名单，请联系网站管理员！');
                } else {
                    if (!empty($findUser['more'])) $findUser['more'] = json_decode($findUser['more'], true);
                    //session('user', $findUser); //user是前台用户的
                    $this->_pSession($findUser["id"], $findUser["user_login"]);      //写入后台管理员session

                    $token = cmf_generate_user_token($findUser["id"], 'web');
                    if (!empty($token)) {
                        session('token', $token);
                    }

                    //判断用户是否有role和zzjg
                    $ups = new UserPublicService;
                    $b = $ups->checkUserRoleAndZzjg($findUser['id']);
                    if (!$b) $this->success("登陆成功", $this->_getLoginRedirect());
                    $this->success("跳转到绑定角色和组织机构页","/xmgl/public/wxUserBind");
                }
            } else {
                $needRegister = true;
            }
        }
        if ($needRegister) {
            //本地用户中创建对应一条数据
            $newUserData = [
                'user_nickname'   => $userInfo['nickname'],
                'avatar'          => $userInfo['avatar'],
                'last_login_time' => time(),
                'last_login_ip'   => get_client_ip(0, true),
                'create_time'     => time(),
                'user_status'     => '1',
                "user_type"       => '1',   //1-admin，2-会员
            ];

            Db::startTrans();
            $result = true;
            try {
                $newUserId = Db::name('user')->insertGetId($newUserData);
                if ($newUserId) {
                    //第三方用户表中创建数据
                    $newThirdPartyUserData = [
                        'user_id'         => $newUserId,
                        'last_login_time' => time(),
                        'expire_time'     => intval(time() + $token['expires_in']),
                        'create_time'     => time(),
                        'login_times'     => 1,
                        'status'          => 1,
                        'nickname'        => $userInfo['nickname'],
                        'third_party'     => $type,
                        'app_id'          => '',
                        'last_login_ip'   => get_client_ip(0, true),
                        'access_token'    => $token['access_token'],
                        'openid'          => $token['openid'],
                        'union_id'         => $userInfo['union_id'],     //WEB和小程序绑定开放平台后，同一个微信用户union_id是一样的
                    ];

                    Db::name('third_party_user')->insert($newThirdPartyUserData);
                    $newUserData = Db::name('user')->where('id', $newUserId)->find();

                    //session('user', $newUserData);      //user是前台用户的
                    $this->_pSession($newUserData["id"], $newUserData["user_login"]);      //写入后台管理员session

                } else {
                    $result = false;
                }
                Db::commit();
            } catch (\Exception $e) {
                //var_dump($e);
                return;
                $result = false;
                Db::rollback();
            }
            if ($result) {
                $this->success("跳转到绑定角色和组织机构页","/xmgl/public/wxUserBind");
                //$this->success("登陆成功", $this->_getLoginRedirect());
            } else {
                $this->error("登陆失败2！", $this->_getLoginRedirect());
            }
        }
    }

    /**
     * 获取登录跳转地址
     */
    private function _getLoginRedirect()
    {
        $sessionLoginHttpReferer = session('login_http_referer');
        //return empty($sessionLoginHttpReferer) ? cmf_get_root() . "/admin" : $sessionLoginHttpReferer;
        return "/admin";
    }

    /**
     * 登陆成功后写入session
     */
    private function _pSession($userId, $user_login)
    {
        /**修改成后台用户登陆 START*/
        session('ADMIN_ID', $userId);
        session('name', $user_login);
        cookie("admin_username", $user_login, 3600 * 24 * 30);
        //session("__LOGIN_BY_CMF_ADMIN_PW__", null);
        /**修改成后台用户登陆 END*/
    }
}
